import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {
    getCommentDetail as getCommentDetailApi,
    getCommentList as getCommentListApi,
    replyComment as replyCommentApi,
    updateCommentStatus as updateCommentStatusApi
} from '@/api/comment'

/**
 * 评论管理Store
 * 管理评论列表、评论详情、评论状态等数据
 */
export const useCommentStore = defineStore('comment', () => {
    // 状态
    const comments = ref([])
    const currentComment = ref(null)
    const commentStatistics = ref(null)
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    // 评论状态映射
    const commentStatusMap = {
        0: {text: '隐藏', type: 'danger'},
        1: {text: '显示', type: 'success'}
    }

    // 评分星级映射
    const ratingMap = {
        1: {text: '1星', color: '#ff4d4f'},
        2: {text: '2星', color: '#ff7a45'},
        3: {text: '3星', color: '#ffa940'},
        4: {text: '4星', color: '#52c41a'},
        5: {text: '5星', color: '#1890ff'}
    }

    // 计算属性
    const commentCount = computed(() => comments.value.length)
    const hasComments = computed(() => comments.value.length > 0)

    /**
     * 获取评论列表
     * @param {Object} params 查询参数
     */
    const getCommentList = async (params = {}) => {
        loading.value = true
        try {
            const response = await getCommentListApi({
                current: currentPage.value,
                size: pageSize.value,
                ...params
            })

            if (response.data) {
                comments.value = response.data.records || []
                total.value = response.data.total || 0
                currentPage.value = response.data.current || 1
            }

            return response
        } catch (error) {
            console.error('获取评论列表失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取评论详情
     * @param {number} id 评论ID
     */
    const getCommentDetail = async (id) => {
        loading.value = true
        try {
            const response = await getCommentDetailApi(id)
            if (response.data) {
                currentComment.value = response.data
            }
            return response
        } catch (error) {
            console.error('获取评论详情失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 更新评论状态
     * @param {number} id 评论ID
     * @param {number} status 状态值
     */
    const updateCommentStatus = async (id, status) => {
        loading.value = true
        try {
            const response = await updateCommentStatusApi(id, status)
            // 更新成功后刷新列表
            await getCommentList()
            return response
        } catch (error) {
            console.error('更新评论状态失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 商家回复评论
     * @param {number} id 评论ID
     * @param {Object} replyData 回复数据
     */
    const replyComment = async (id, replyData) => {
        loading.value = true
        try {
            const response = await replyCommentApi(id, replyData)
            // 回复成功后刷新列表
            await getCommentList()
            return response
        } catch (error) {
            console.error('回复评论失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 删除评论
     * @param {number} id 评论ID
     */
    const deleteComment = async (id) => {
        loading.value = true
        try {
            const response = await request.delete(`/admin/comments/${id}`)
            // 删除成功后刷新列表
            await getCommentList()
            return response
        } catch (error) {
            console.error('删除评论失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 批量更新评论状态
     * @param {Array} ids 评论ID数组
     * @param {number} status 状态值
     */
    const batchUpdateCommentStatus = async (ids, status) => {
        loading.value = true
        try {
            const response = await request.put('/admin/comments/batch/status', {
                ids,
                status
            })
            // 更新成功后刷新列表
            await getCommentList()
            return response
        } catch (error) {
            console.error('批量更新评论状态失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取评论统计信息
     */
    const getCommentStatistics = async () => {
        loading.value = true
        try {
            const response = await request.get('/admin/comments/statistics')
            if (response.data) {
                commentStatistics.value = response.data
            }
            return response
        } catch (error) {
            console.error('获取评论统计失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 设置分页参数
     * @param {number} page 页码
     * @param {number} size 每页大小
     */
    const setPagination = (page, size) => {
        currentPage.value = page
        pageSize.value = size
    }

    /**
     * 获取评论状态显示信息
     * @param {number} status 状态值
     */
    const getCommentStatusInfo = (status) => {
        return commentStatusMap[status] || {text: '未知', type: 'info'}
    }

    /**
     * 获取评分显示信息
     * @param {number} rating 评分值
     */
    const getRatingInfo = (rating) => {
        return ratingMap[rating] || {text: '未评分', color: '#d9d9d9'}
    }

    /**
     * 格式化评论内容（截取显示）
     * @param {string} content 评论内容
     * @param {number} maxLength 最大长度
     */
    const formatCommentContent = (content, maxLength = 50) => {
        if (!content) return ''
        return content.length > maxLength ? content.substring(0, maxLength) + '...' : content
    }

    /**
     * 重置状态
     */
    const resetState = () => {
        comments.value = []
        currentComment.value = null
        commentStatistics.value = null
        loading.value = false
        total.value = 0
        currentPage.value = 1
        pageSize.value = 10
    }

    return {
        // 状态
        comments,
        currentComment,
        commentStatistics,
        loading,
        total,
        currentPage,
        pageSize,

        // 计算属性
        commentCount,
        hasComments,

        // 方法
        getCommentList,
        getCommentDetail,
        updateCommentStatus,
        replyComment,
        deleteComment,
        batchUpdateCommentStatus,
        getCommentStatistics,
        setPagination,
        getCommentStatusInfo,
        getRatingInfo,
        formatCommentContent,
        resetState
    }
})
